import { getCategoryList} from '../../api/store.js';
/**选择地址 */
import { getCity } from '../../api/api.js';


import { editAddressCate, getAddressDetailCate, editAddressCateByMap, getAddressDetailCateByMap } from '../../api/user.js';


const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navlist: [],
    productList: [],
    navActive: 0,
    parameter: {
      'navbar': '1',
      'return': '1',
      'title':'产品分类',
    },
    navH:"",
    number:"",


    /**省市区所需参数 */
    region: ['省', '市', '区'],
    valueRegion: [0, 0, 0],
    cityId: 0,
    district: [],
    multiArray: [],
    multiIndex: [0, 0, 0],
    isGoIndex: true,
    iShidden: false,
    /*产品分类样式 */
    IMG_URL:"http://try11.jiaodaoren.com/zhusiyao/qiaomeijiaren/",
    /**新增元素 */
    userAddress:[],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (res) {
    this.getUserAddressCate();

    this.getAllCategory();

    this.getCityList();

    

  },
  getUserAddressCate: function () {
    let that = this;
    console.log("getUserAddressCate");
    getAddressDetailCate().then(res => {
      console.log('得到地址', res.data);
      var region = [res.data.province, res.data.city, res.data.district];
      that.setData({
        userAddress: res.data,
        region: region,
        cityId: res.data.city_id,
      });
    });
  },
  /*获取地址列表* */
  getCityList: function () {
    let that = this;
    getCity().then(res => {
      console.log('获取地址',res);
      that.setData({ district: res.data });
      that.initialize();
    })
  },
  /**选择地区*/
  bindRegionChange: function (e) {
    console.log('开始改变');
    let multiIndex = this.data.multiIndex, province = this.data.district[multiIndex[0]] || { c: [] }, city = province.c[multiIndex[1]] || { v: 0 }, multiArray = this.data.multiArray, value = e.detail.value;
    console.log(value);
    console.log(province);
    this.setData({
      region: [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]],
      cityId: city.v,
      valueRegion: [0, 0, 0]
    });
    this.initialize();

    // /**用户保存地址数据 */
    // var value_attr = new Array();
    // value_attr[0] = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]];
    // value_attr[1] = city.v;
    // console.log('修改地址', value_attr);
    // this.editAddressCate(value_attr);

    this.local_shop();
  },
  /**本地商品 */
  local_shop: function () {
    var multiArray = this.data.multiArray
    var region = this.data.region;
    /**用户保存地址数据 */
    var value_attr = new Array();
    // value_attr[0] = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]];
    value_attr[0] =[region[0], region[1], region[2]];
    // value_attr[1] = city.v;
    value_attr[1] = this.data.cityId;
    console.log('修改地址', value_attr);
    this.editAddressCate(value_attr);



    // var region = this.data.region;
    // wx.navigateTo({
    //   url: '/pages/goods_list/goods_list?city_name=' + region[1],
    // })
  },

  editAddressCate: function (value){
    editAddressCate(value).then(res => {
      // if (that.data.id)
      //   app.Tips({ title: '修改成功', icon: 'success' });
      // else
      //   app.Tips({ title: '添加成功', icon: 'success' });

      /**修改成功跳地址 */
      var region = this.data.region;
      wx.navigateTo({
        url: '/pages/goods_list/goods_list?city_name=' + region[1],
      })


      // setTimeout(function () {
      //     wx.navigateTo({
      //       url: 'pages/goods_list/goods_list?is_address='+value[1],
      //     })
      // }, 1000);
    }).catch(err => {
      return app.Tips({ title: err });
    })
  },
  /**选择地区列改变 */
  initialize: function () {
    let that = this, province = [], city = [], area = [];
    if (that.data.district.length) {
      let cityChildren = that.data.district[0].c || [];
      let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
      that.data.district.forEach(function (item) {
        province.push(item.n);
      });
      cityChildren.forEach(function (item) {
        city.push(item.n);
      });
      areaChildren.forEach(function (item) {
        area.push(item.n);
      });
      that.setData({
        multiArray: [province, city, area],
      });
    }

    
    
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('改变列');
    let that = this, column = e.detail.column, value = e.detail.value, currentCity = this.data.district[value] || { c: [] }, multiArray = that.data.multiArray, multiIndex = that.data.multiIndex;
    multiIndex[column] = value;
    switch (column) {
      case 0:
        let areaList = currentCity.c[0] || { c: [] };
        multiArray[1] = currentCity.c.map((item) => {
          return item.n;
        });
        multiArray[2] = areaList.c.map((item) => {
          return item.n;
        });
        break;
      case 1:
        let cityList = that.data.district[multiIndex[0]].c[multiIndex[1]].c || [];
        multiArray[2] = cityList.map((item) => {
          return item.n;
        });
        break;
      case 2:

        break;
    }
    this.setData({ multiArray: multiArray, multiIndex: multiIndex });
  },
  infoScroll:function(){
    let that = this;
    let len = that.data.productList.length;
    that.setData({
      navH: app.globalData.navHeight,
      number: that.data.productList[len - 1].children.length
    })
    //设置商品列表高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: (res.windowHeight) * ( 750/res.windowWidth) - 98 - app.globalData.navHeight
          //res.windowHeight:获取整个窗口高度为px，*2为rpx；98为头部占据的高度；
        })
      },
    });
    var height = 0;
    var hightArr = [];
    for (var i = 0; i < len; i++) { //productList
      //获取元素所在位置
      var query = wx.createSelectorQuery().in(this);
      var idView = "#b" + i;
      query.select(idView).boundingClientRect();
      query.exec(function (res) {
        var top = res[0].top;
        hightArr.push(top);
        that.setData({
          hightArr: hightArr
        });
      });
    };
  },
  tap: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    this.setData({
      toView: id,
      navActive: index
    });
  },
  getAllCategory:function(){
    var that = this;
    getCategoryList().then(res=>{
      that.setData({
        productList: res.data
      });
      that.infoScroll();
    })
  },
  scroll: function (e) {
    var scrollTop = e.detail.scrollTop;
    var scrollArr = this.data.hightArr;
    for (var i = 0; i < scrollArr.length; i++) {
      if (scrollTop >= 0 && scrollTop < scrollArr[1] - scrollArr[0]) {
        this.setData({
          navActive: 0,
          lastActive: 0
        })
      } else if (scrollTop >= scrollArr[i] - scrollArr[0] && scrollTop < scrollArr[i + 1] - scrollArr[0]) {
        this.setData({
          navActive: i
        })
      } else if (scrollTop >= scrollArr[scrollArr.length - 1] - scrollArr[0]) {
        this.setData({
          navActive: scrollArr.length - 1
        })
      }
    }
  },

  searchSubmitValue: function (e) {
    if (e.detail.value.length > 0) 
      wx.navigateTo({ url: '/pages/goods_list/goods_list?searchValue=' + e.detail.value})
    else 
      return app.Tips({ title:'请填写要搜索的产品信息'});
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


    // this.getProvinceByMap();


  },

  getProvinceByMap() {
    /**只执行一次的方法 */
    const _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude

        console.log('latitude', latitude);
        console.log('longitude', longitude);

        demo.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            var address_info = res.result;
            var address_component = address_info.address_component;
            var location = address_info.location;
            console.log('address_info', address_info);
            var value_attr = { detail: address_info.address, province: address_component.province, city: address_component.city, district: address_component.district, longitude: location.lng, latitude: location.lat };
            console.log('value_attr', value_attr);
            _this.editAddressCateByMap(value_attr);
            /**发送post地址 */
          },
          fail: function (res) {
            console.log(res);
          },
        })
      }
    })
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  }
})